package cn.edu.stu.contorller.system;

import cn.edu.stu.bean.AjaxResult;
import cn.edu.stu.manager.AsyncManager;
import cn.edu.stu.manager.factory.AsyncFactory;
import cn.edu.stu.service.RecordService;
import cn.edu.stu.service.SongService;
import cn.edu.stu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Karl
 * @Date 2022/12/26 - 14:04
 */

@Controller
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    SongService songService;

    @Autowired
    RecordService recordService;

    @RequestMapping("/bg/user/delete/{id}")
    public String deleteUser(@PathVariable("id") long userId,
                             HttpServletRequest request){
        Long owner = (Long) request.getAttribute("userid");
        if(owner==1 )
            userService.deleteByUid(userId);

        return "forward:/bg/basic_table";
    }


    @RequestMapping("/bg/song/delete/{id}")
    public String deleteSong(@PathVariable("id") int songId,
                             HttpServletRequest request){
        Long owner = (Long) request.getAttribute("userid");
        if(owner==1&&songService.deleteBySongId(songId)){
            AsyncManager.me().execute(AsyncFactory.checkDeleteSongFile(songId));
        }


        return "forward:/bg/dynamic_table";
    }


    @RequestMapping("/bg/record/delete/{id}")
    public String deleteRecord(@PathVariable("id") int songId,
                             HttpServletRequest request){
        Long userId = (Long) request.getAttribute("userid");
        AjaxResult result = recordService.deleteRecordBySongId(songId, userId);
        if(result.getCode()==1){
            //启用异步线程去完成检查是否需要删除该歌曲文件
            AsyncManager.me().execute(AsyncFactory.checkDeleteSongFile(songId));
        }
        return "forward:/bg/responsive_table";
    }

}
